const express = require('express');
const router = express.Router();
const { pool } = require('../config/database');

// 获取所有分类（树形结构）
router.get('/tree', async (req, res) => {
  try {
    const [categories] = await pool.execute(
      'SELECT * FROM category WHERE is_deleted = 0 ORDER BY order_num ASC, id ASC'
    );
    
    // 构建树形结构
    const buildTree = (items, parentId = 0) => {
      return items
        .filter(item => item.parent_id === parentId)
        .map(item => ({
          ...item,
          children: buildTree(items, item.id)
        }));
    };
    
    const tree = buildTree(categories);
    
    res.json({
      success: true,
      message: '获取分类树成功',
      data: tree
    });
  } catch (error) {
    console.error('获取分类树失败:', error);
    res.status(500).json({
      success: false,
      message: '获取分类树失败',
      error: error.message
    });
  }
});

// 获取所有分类（列表）
router.get('/list', async (req, res) => {
  try {
    const [categories] = await pool.execute(
      'SELECT * FROM category WHERE is_deleted = 0 ORDER BY order_num ASC, id ASC'
    );
    
    res.json({
      success: true,
      message: '获取分类列表成功',
      data: categories
    });
  } catch (error) {
    console.error('获取分类列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取分类列表失败',
      error: error.message
    });
  }
});

// 根据ID获取分类
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const [rows] = await pool.execute(
      'SELECT * FROM category WHERE id = ? AND is_deleted = 0',
      [id]
    );
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '分类不存在'
      });
    }
    
    res.json({
      success: true,
      message: '获取分类信息成功',
      data: rows[0]
    });
  } catch (error) {
    console.error('获取分类信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取分类信息失败',
      error: error.message
    });
  }
});

// 获取指定父分类下的子分类
router.get('/children/:parentId', async (req, res) => {
  try {
    const { parentId } = req.params;
    const [rows] = await pool.execute(
      'SELECT * FROM category WHERE parent_id = ? AND is_deleted = 0 ORDER BY order_num ASC',
      [parentId]
    );
    
    res.json({
      success: true,
      message: '获取子分类成功',
      data: rows
    });
  } catch (error) {
    console.error('获取子分类失败:', error);
    res.status(500).json({
      success: false,
      message: '获取子分类失败',
      error: error.message
    });
  }
});

// 添加分类
router.post('/add', async (req, res) => {
  try {
    const { name, image_url, parent_id, status, order_num } = req.body;
    
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '分类名称不能为空'
      });
    }
    
    const [result] = await pool.execute(
      'INSERT INTO category (name, image_url, parent_id, status, order_num) VALUES (?, ?, ?, ?, ?)',
      [
        name,
        image_url || null,
        parent_id || 0,
        status !== undefined ? status : 1,
        order_num || 0
      ]
    );
    
    res.json({
      success: true,
      message: '添加分类成功',
      data: {
        id: result.insertId,
        name,
        image_url,
        parent_id: parent_id || 0,
        status: status !== undefined ? status : 1,
        order_num: order_num || 0
      }
    });
  } catch (error) {
    console.error('添加分类失败:', error);
    res.status(500).json({
      success: false,
      message: '添加分类失败',
      error: error.message
    });
  }
});

// 更新分类
router.put('/update/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, image_url, parent_id, status, order_num } = req.body;
    
    const [existingCategory] = await pool.execute(
      'SELECT * FROM category WHERE id = ? AND is_deleted = 0',
      [id]
    );
    
    if (existingCategory.length === 0) {
      return res.status(404).json({
        success: false,
        message: '分类不存在'
      });
    }
    
    await pool.execute(
      'UPDATE category SET name = ?, image_url = ?, parent_id = ?, status = ?, order_num = ? WHERE id = ?',
      [
        name,
        image_url,
        parent_id,
        status,
        order_num,
        id
      ]
    );
    
    res.json({
      success: true,
      message: '更新分类成功'
    });
  } catch (error) {
    console.error('更新分类失败:', error);
    res.status(500).json({
      success: false,
      message: '更新分类失败',
      error: error.message
    });
  }
});

// 删除分类（软删除）
router.delete('/delete/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const [existingCategory] = await pool.execute(
      'SELECT * FROM category WHERE id = ? AND is_deleted = 0',
      [id]
    );
    
    if (existingCategory.length === 0) {
      return res.status(404).json({
        success: false,
        message: '分类不存在'
      });
    }
    
    // 检查是否有子分类
    const [children] = await pool.execute(
      'SELECT * FROM category WHERE parent_id = ? AND is_deleted = 0',
      [id]
    );
    
    if (children.length > 0) {
      return res.status(400).json({
        success: false,
        message: '该分类下存在子分类，无法删除'
      });
    }
    
    await pool.execute(
      'UPDATE category SET is_deleted = 1 WHERE id = ?',
      [id]
    );
    
    res.json({
      success: true,
      message: '删除分类成功'
    });
  } catch (error) {
    console.error('删除分类失败:', error);
    res.status(500).json({
      success: false,
      message: '删除分类失败',
      error: error.message
    });
  }
});

module.exports = router;